<template>
  <div class="coupon-list-page">
    <div class="container">
      <div class="page-header">
        <h1>我的优惠券</h1>
      </div>

      <!-- 优惠券统计 -->
      <el-card class="coupon-stats">
        <div class="stats-content">
          <div class="stat-item">
            <h3>{{ couponStats.total }}</h3>
            <p>全部优惠券</p>
          </div>
          <div class="stat-item">
            <h3>{{ couponStats.available }}</h3>
            <p>可使用</p>
          </div>
          <div class="stat-item">
            <h3>{{ couponStats.used }}</h3>
            <p>已使用</p>
          </div>
          <div class="stat-item">
            <h3>{{ couponStats.expired }}</h3>
            <p>已过期</p>
          </div>
        </div>
      </el-card>

      <!-- 筛选标签 -->
      <el-card class="filter-section">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="可使用" name="available" />
          <el-tab-pane label="已使用" name="used" />
          <el-tab-pane label="已过期" name="expired" />
        </el-tabs>
      </el-card>

      <!-- 优惠券列表 -->
      <div class="coupon-list" v-loading="loading">
        <div v-if="coupons.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无优惠券">
            <el-button type="primary" @click="goToHome">去首页看看</el-button>
          </el-empty>
        </div>

        <div
          v-for="coupon in coupons"
          :key="coupon.id"
          class="coupon-item"
          :class="{
            'available': coupon.status === 'available',
            'used': coupon.status === 'used',
            'expired': coupon.status === 'expired'
          }"
          @click="showCouponDetail(coupon)"
        >
          <!-- 优惠券左侧 -->
          <div class="coupon-left">
            <div class="coupon-value">
              <span class="symbol">¥</span>
              <span class="amount">{{ coupon.amount }}</span>
            </div>
            <div class="coupon-condition" v-if="coupon.minAmount > 0">
              满{{ coupon.minAmount }}可用
            </div>
            <div class="coupon-condition" v-else>
              无门槛
            </div>
          </div>

          <!-- 优惠券右侧 -->
          <div class="coupon-right">
            <div class="coupon-header">
              <h3 class="coupon-title">{{ coupon.title }}</h3>
              <el-tag 
                :type="getStatusTagType(coupon.status)" 
                size="small"
              >
                {{ getStatusText(coupon.status) }}
              </el-tag>
            </div>

            <p class="coupon-description">{{ coupon.description }}</p>

            <div class="coupon-meta">
              <div class="coupon-time">
                <el-icon><Clock /></el-icon>
                <span v-if="coupon.status === 'available'">
                  {{ formatValidTime(coupon.validUntil) }}
                </span>
                <span v-else-if="coupon.status === 'used'">
                  {{ formatDate(coupon.usedAt) }} 已使用
                </span>
                <span v-else>
                  {{ formatDate(coupon.validUntil) }} 已过期
                </span>
              </div>
              <div class="coupon-scope" v-if="coupon.scope">
                <el-icon><Shop /></el-icon>
                <span>{{ getScopeText(coupon.scope) }}</span>
              </div>
            </div>

            <div class="coupon-actions" v-if="coupon.status === 'available'">
              <el-button 
                size="small" 
                type="primary" 
                @click.stop="useCoupon(coupon)"
              >
                立即使用
              </el-button>
            </div>
          </div>

          <!-- 状态标记 -->
          <div class="status-mark" v-if="coupon.status !== 'available'">
            <span v-if="coupon.status === 'used'">已使用</span>
            <span v-else>已过期</span>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button @click="loadMore" :loading="loadingMore">
          加载更多
        </el-button>
      </div>
    </div>

    <!-- 优惠券详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="优惠券详情"
      width="500px"
    >
      <div class="coupon-detail" v-if="selectedCoupon">
        <!-- 优惠券卡片 -->
        <div class="detail-coupon-card" :class="selectedCoupon.status">
          <div class="detail-left">
            <div class="detail-value">
              <span class="symbol">¥</span>
              <span class="amount">{{ selectedCoupon.amount }}</span>
            </div>
            <div class="detail-condition" v-if="selectedCoupon.minAmount > 0">
              满{{ selectedCoupon.minAmount }}可用
            </div>
            <div class="detail-condition" v-else>
              无门槛
            </div>
          </div>
          <div class="detail-right">
            <h3>{{ selectedCoupon.title }}</h3>
            <p>{{ selectedCoupon.description }}</p>
          </div>
        </div>

        <!-- 优惠券信息 -->
        <div class="detail-info">
          <div class="info-row">
            <span class="label">优惠券类型</span>
            <span class="value">{{ getTypeText(selectedCoupon.type) }}</span>
          </div>
          <div class="info-row">
            <span class="label">使用条件</span>
            <span class="value">
              {{ selectedCoupon.minAmount > 0 ? `满${selectedCoupon.minAmount}元可用` : '无门槛' }}
            </span>
          </div>
          <div class="info-row">
            <span class="label">适用范围</span>
            <span class="value">{{ getScopeText(selectedCoupon.scope) }}</span>
          </div>
          <div class="info-row">
            <span class="label">有效期</span>
            <span class="value">
              {{ formatDate(selectedCoupon.validFrom) }} 至 {{ formatDate(selectedCoupon.validUntil) }}
            </span>
          </div>
          <div class="info-row" v-if="selectedCoupon.status === 'used'">
            <span class="label">使用时间</span>
            <span class="value">{{ formatDateTime(selectedCoupon.usedAt) }}</span>
          </div>
          <div class="info-row" v-if="selectedCoupon.orderNumber">
            <span class="label">关联订单</span>
            <el-button 
              link 
              type="primary" 
              @click="goToOrder(selectedCoupon.orderNumber)"
            >
              {{ selectedCoupon.orderNumber }}
            </el-button>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button 
            v-if="selectedCoupon?.status === 'available'"
            type="primary" 
            @click="useCoupon(selectedCoupon)"
          >
            立即使用
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Clock, Shop } from '@element-plus/icons-vue'
import { couponApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const coupons = ref([])
const loading = ref(true)
const loadingMore = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)
const activeTab = ref('all')
const showDetailDialog = ref(false)
const selectedCoupon = ref(null)

const couponStats = reactive({
  total: 0,
  available: 0,
  used: 0,
  expired: 0
})

// 生命周期
onMounted(() => {
  fetchCoupons()
  fetchCouponStats()
})

// 方法定义
const fetchCoupons = async (reset = true) => {
  try {
    if (reset) {
      loading.value = true
      page.value = 1
    } else {
      loadingMore.value = true
    }

    const params = {
      page: page.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'all' ? undefined : activeTab.value
    }

    const response = await couponApi.getCouponList(params)
    const { data, total } = response.data
    
    if (reset) {
      coupons.value = data
    } else {
      coupons.value.push(...data)
    }

    hasMore.value = coupons.value.length < total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const fetchCouponStats = async () => {
  try {
    const response = await couponApi.getCouponStats()
    Object.assign(couponStats, response.data)
  } catch (error) {
    console.error('获取优惠券统计失败:', error)
  }
}

const handleTabChange = (tab) => {
  activeTab.value = tab
  fetchCoupons()
}

const loadMore = () => {
  page.value++
  fetchCoupons(false)
}

const showCouponDetail = (coupon) => {
  selectedCoupon.value = coupon
  showDetailDialog.value = true
}

const useCoupon = (coupon) => {
  // 跳转到商家列表或服务列表，根据优惠券的适用范围
  if (coupon.scope === 'merchant' && coupon.merchantId) {
    router.push(`/merchants/${coupon.merchantId}`)
  } else if (coupon.scope === 'service' && coupon.serviceId) {
    router.push(`/services/${coupon.serviceId}`)
  } else {
    router.push('/services')
  }
}

const goToOrder = (orderNumber) => {
  router.push(`/orders/${orderNumber}`)
}

const goToHome = () => {
  router.push('/home')
}

const getStatusTagType = (status) => {
  const typeMap = {
    available: 'success',
    used: 'info',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    available: '可使用',
    used: '已使用',
    expired: '已过期'
  }
  return textMap[status] || '未知'
}

const getTypeText = (type) => {
  const textMap = {
    discount: '满减券',
    percentage: '折扣券',
    cashback: '返现券'
  }
  return textMap[type] || '优惠券'
}

const getScopeText = (scope) => {
  const textMap = {
    all: '全平台通用',
    merchant: '指定商家',
    service: '指定服务',
    category: '指定分类'
  }
  return textMap[scope] || '全平台通用'
}

const formatValidTime = (date) => {
  const now = dayjs()
  const validDate = dayjs(date)
  const diffDays = validDate.diff(now, 'day')
  
  if (diffDays < 0) {
    return '已过期'
  } else if (diffDays === 0) {
    return '今日到期'
  } else if (diffDays === 1) {
    return '明日到期'
  } else if (diffDays <= 7) {
    return `${diffDays}天后到期`
  } else {
    return `有效期至 ${validDate.format('MM-DD')}`
  }
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style lang="scss" scoped>
.coupon-list-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }
}

.el-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.coupon-stats {
  .stats-content {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;

    .stat-item {
      text-align: center;

      h3 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #333;
      }

      p {
        margin: 0;
        font-size: 14px;
        color: #666;
      }
    }
  }
}

.filter-section {
  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__nav-wrap::after) {
    display: none;
  }
}

.coupon-list {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }
}

.coupon-item {
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  display: flex;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  &.available {
    border-left: 4px solid #67c23a;

    .coupon-left {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
      color: white;
    }
  }

  &.used {
    opacity: 0.7;
    
    .coupon-left {
      background: linear-gradient(135deg, #909399 0%, #b3b3b3 100%);
      color: white;
    }
  }

  &.expired {
    opacity: 0.7;
    
    .coupon-left {
      background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
      color: white;
    }
  }

  .coupon-left {
    width: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    color: white;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      right: -8px;
      top: 50%;
      transform: translateY(-50%);
      width: 16px;
      height: 16px;
      background: #f5f7fa;
      border-radius: 50%;
    }

    .coupon-value {
      display: flex;
      align-items: baseline;
      margin-bottom: 4px;

      .symbol {
        font-size: 14px;
        font-weight: 500;
      }

      .amount {
        font-size: 28px;
        font-weight: 600;
        margin-left: 2px;
      }
    }

    .coupon-condition {
      font-size: 12px;
      opacity: 0.9;
    }
  }

  .coupon-right {
    flex: 1;
    padding: 16px 20px;
    display: flex;
    flex-direction: column;

    .coupon-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;

      .coupon-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
        flex: 1;
        margin-right: 12px;
      }
    }

    .coupon-description {
      margin: 0 0 12px 0;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
    }

    .coupon-meta {
      display: flex;
      flex-direction: column;
      gap: 4px;
      margin-bottom: 12px;

      .coupon-time,
      .coupon-scope {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #999;

        .el-icon {
          margin-right: 4px;
        }
      }
    }

    .coupon-actions {
      margin-top: auto;
    }
  }

  .status-mark {
    position: absolute;
    top: 16px;
    right: 16px;
    transform: rotate(12deg);
    background: rgba(0, 0, 0, 0.1);
    color: white;
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
  }
}

.load-more {
  text-align: center;
  margin-top: 24px;
}

.coupon-detail {
  .detail-coupon-card {
    display: flex;
    background: white;
    border-radius: 8px;
    margin-bottom: 20px;
    overflow: hidden;
    border: 1px solid #e4e7ed;

    &.available {
      border-color: #67c23a;
    }

    &.used {
      opacity: 0.7;
    }

    &.expired {
      opacity: 0.7;
    }

    .detail-left {
      width: 120px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
      color: white;

      .detail-value {
        display: flex;
        align-items: baseline;
        margin-bottom: 4px;

        .symbol {
          font-size: 14px;
          font-weight: 500;
        }

        .amount {
          font-size: 24px;
          font-weight: 600;
          margin-left: 2px;
        }
      }

      .detail-condition {
        font-size: 12px;
        opacity: 0.9;
      }
    }

    .detail-right {
      flex: 1;
      padding: 16px;

      h3 {
        margin: 0 0 8px 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    &.available .detail-left {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    }

    &.used .detail-left {
      background: linear-gradient(135deg, #909399 0%, #b3b3b3 100%);
    }

    &.expired .detail-left {
      background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    }
  }

  .detail-info {
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

      .label {
        font-size: 14px;
        color: #666;
        min-width: 80px;
      }

      .value {
        font-size: 14px;
        color: #333;
        text-align: right;
        flex: 1;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .coupon-stats {
    .stats-content {
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
    }
  }

  .coupon-item {
    flex-direction: column;

    .coupon-left {
      width: 100%;
      height: 80px;
      flex-direction: row;
      justify-content: center;

      &::after {
        display: none;
      }

      .coupon-value {
        margin-right: 16px;
        margin-bottom: 0;
      }
    }

    .coupon-right {
      padding: 12px 16px;

      .coupon-meta {
        flex-direction: row;
        justify-content: space-between;
      }
    }

    .status-mark {
      top: 12px;
      right: 12px;
    }
  }

  .detail-coupon-card {
    flex-direction: column !important;

    .detail-left {
      width: 100% !important;
      height: 80px;
      flex-direction: row;
      justify-content: center;

      .detail-value {
        margin-right: 16px;
        margin-bottom: 0;
      }
    }
  }
}
</style> 